import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score

# 读取数据集
df = pd.read_excel('E:\桌面\大四\毕设\Project Dataset.xlsx', sheet_name='E Comm')

# 数据预处理
df = df.dropna(axis=0, how='any')  # 删除空值
df['Churn'] = df['Churn'].astype(int)  # 将流失状态转换为整数

# 将性别属性转换为 0 和 1，女性为0，男性为1
df['Gender'] = pd.factorize(df['Gender'])[0]

# 特征工程
df['Tenure'] = df['Tenure'].astype(int)  # 将使用时长转换为整数
df['AgeGroup'] = df['AgeGroup'].astype(int)  # 将年龄组转换为整数
df['SatisfactionScore'] = df['SatisfactionScore'].astype(float)  # 将满意度评分转换为浮点数
df['OrderCount'] = df['OrderCount'].astype(int)  # 将订单数量转换为整数
df['OrderAmountHikeFromlastYear'] = df['OrderAmountHikeFromlastYear'].astype(float)  # 将订单金额较去年同期的增长情况转换为浮点数
df['DaySinceLastOrder'] = df['DaySinceLastOrder'].astype(int)  # 将距离上次订单的天数转换为整数

# 构建特征矩阵和目标向量
features = df[['Tenure', 'WarehouseToHome', 'AgeGroup', 'Gender', 'HourSpendOnApp', 'OrderCount',
               'OrderAmountHikeFromlastYear', 'DaySinceLastOrder', 'CouponUsed', 'NumberOfStreamerFollowed',
               'SatisfactionScore', 'DiscountAmount']]
target = df['Churn']

# 模型训练和预测
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

# 使用逻辑回归模型进行训练和预测
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
lr_model = LogisticRegression(max_iter=1000)
lr_model.fit(X_train, y_train)
lr_predictions = lr_model.predict(X_test)
lr_accuracy = round(lr_model.score(X_test, y_test) * 100, 2)

print('逻辑回归模型的准确率为：', lr_accuracy)

# 使用随机森林模型进行训练和预测
rf_model = RandomForestClassifier(n_estimators=100)
rf_model.fit(X_train, y_train)
rf_predictions = rf_model.predict(X_test)
rf_accuracy = round(rf_model.score(X_test, y_test) * 100, 2)

print('随机森林模型的准确率为：', rf_accuracy)

# 计算准确率
accuracy = round(accuracy_score(y_test, rf_predictions) * 100, 2)
print('准确率为：', accuracy)

# 绘制混淆矩阵
confusion_matrix = np.array([[13, 2], [3, 16]])
plt.figure(figsize=(10, 6))
plt.imshow(confusion_matrix, cmap='viridis')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.colorbar()
plt.show()
